<template>
  <div class="buildSectionBar" ref="buildSectionBar"></div>
</template>

<script lang="ts">
export default {
  name: "buildSectionBar"
};
</script>

<script setup lang="ts">
import { ECharts } from "echarts";
import echarts from "/@/plugins/echarts";
import { storageLocal } from "/@/utils/storage";
import { onMounted, nextTick, ref, watch } from "vue";
import { tryOnUnmounted, useTimeoutFn } from "@vueuse/core";
import { getSectionInfo } from "/@/api/dashboards";

import {
  addResizeListener,
  removeResizeListener
} from "element-plus/lib/utils/resize-event";

// import { postProjectMngList } from "/@/api/project";

const props = defineProps({
  type: {
    type: String,
    default: "全部"
  },
  typeCode: {
    type: String,
    default: ""
  }
});
const emit = defineEmits(["clickItem"]);

const buildSectionBar = ref<HTMLElement | null>(null) as any;

let echartInstance: ECharts;

// let xAxisData = ref([]);
// let seriesData = ref([]);
let selectedValue = ref("");
let typeValue = ref(props.type);
let projectInfo = storageLocal.getItem("projectInfo");
let civilInfoData = ref({});
let maxVal = ref(1);
// let typeCodeValue = ref(props.typeCode);

// let formInline = reactive({
//   projectNameLike: "",
//   projectRegionCode: "",
//   projectFactoryCode: "",
//   projectLeaderNameLike: "",
//   projectTypeCode: "",
//   projectYear: "",
//   createTimeStrStart: "",
//   createTimeStrEnd: "",
//   pageNum: 1,
//   pageSize: 10
// });

const initChart = (xAxis, yData1, yData2, yData3) => {
  if (!echartInstance) {
    return;
  }
  echartInstance.setOption({
    title: {
      text: "合同总提单量概览",
      top: 10,
      left: 10,
      textStyle: {
        fontSize: 16,
        fontWeight: "normal"
      }
    },
    color: ["#5dd55d", "#5298ff", "#ffd765"],
    grid: {
      x: "13%",
      x2: "13%",
      y: 90,
      y2: 40
      // bottom: "20%",
      // height: "68%",
      // containLabel: true
    },
    legend: { left: "right", padding: [15, 40], itemGap: 60 },
    tooltip: {
      trigger: "item"
    },
    xAxis: {
      type: "category",
      triggerEvent: true,
      position: "bottom",
      // axisTick: {
      //   alignWithLabel: true
      // },
      axisLabel: {
        interval: 0,
        width: "70",
        overflow: "truncate",
        show: true
      },
      data: xAxis
    },
    yAxis: [
      {
        type: "value",
        splitNumber: 5,
        min: 0,
        max: Math.ceil(maxVal.value / 5) * 5,
        interval: (Math.ceil(maxVal.value / 5) * 5) / 5
      },
      {
        type: "value",
        min: 0,
        max: 100,
        splitNumber: 5,
        axisLabel: {
          formatter: "{value}%"
        }
      }
    ],
    // series: seriesData
    series: [
      {
        name: "提单率/完成率",
        tooltip: {
          valueFormatter: function (value) {
            return value + "%";
          }
        },
        data: yData3,
        type: "line",
        yAxisIndex: 1
      },
      {
        name: "实际完成量",
        data: yData2,
        type: "bar",
        barMaxWidth: 20
      },
      {
        name: "实际提单量",
        data: yData1,
        type: "bar",
        barMaxWidth: 20
      }
    ]
  });
};

function initechartInstance(xAxis, yData1, yData2, yData3) {
  const echartDom = document.querySelector(".buildSectionBar");
  if (!echartDom) return;
  // @ts-ignore
  echartInstance = echarts.init(echartDom);
  echartInstance.clear(); //清除旧画布 重新渲染

  initChart(xAxis, yData1, yData2, yData3);

  echartInstance.on("click", function (params) {
    let value = "" as any;
    if (params.componentType == "xAxis") {
      value = params.value;
    } else {
      value = params.name;
    }
    console.log(11, "********", selectedValue.value, value, params);
    if (selectedValue.value && selectedValue.value === value) {
      selectedValue.value = "";
      emit("clickItem", "");
      return;
    }
    selectedValue.value = value;
    emit("clickItem", value);
  });
}

// const initProjectNum = async () => {
//   try {
//     const { code, data } = await postProjectMngList(formInline);
//     if (code === 200) {
//       console.log(11111, data);
//       // xAxisData.value = data.xAxisData;
//       // const dataKey = Object.keys(data.multiSeriesData);
//       // seriesData.value = dataKey.map(item => {
//       //   return {
//       //     name: item,
//       //     data: data.multiSeriesData[item],
//       //     type: "line",
//       //     label: {
//       //       show: true
//       //     }
//       //   };
//       // });
//       nextTick(() => {
//         initechartInstance(xAxisData.value, seriesData.value);
//       });
//     }
//   } catch (err) {
//     console.log(err);
//   }
// };

// initProjectNum();

//获取土建类信息
const getCivilTotalInfo = async () => {
  try {
    const { data } = await getSectionInfo({ projectManageId: projectInfo.id });
    civilInfoData.value = data;
    let xAxis = [],
      yData1 = [],
      yData2 = [],
      yData3 = [];
    data.forEach(item => {
      xAxis.push(item.sectionName);
      yData1.push(item.completeInsCount.civilInsTotal);
      yData2.push(item.completeInsCount.civilCompleteTotal);
      yData3.push(
        item.completeInsCount.civilCompleteTotal
          ? (item.completeInsCount.civilCompleteTotal /
              item.completeInsCount.civilInsTotal) *
              100
          : 0
      );
    });
    maxVal = Math.max.apply(null, yData1);
    nextTick(() => {
      initechartInstance(xAxis, yData1, yData2, yData3);
    });
  } catch (err) {
    console.log(err);
  }
};
getCivilTotalInfo();

onMounted(() => {
  nextTick(() => {
    addResizeListener(buildSectionBar.value, resetRender);
  });
  // useEventListener("resize", () => {
  //   console.log("resize");
  //   if (!echartInstance) return;
  //   useTimeoutFn(() => {
  //     echartInstance.resize();
  //   }, 180);
  // });
});

watch(
  () => props.type,
  newVal => {
    console.log(90, newVal);
    typeValue.value = newVal;
    // initChart();
  }
);

const resetRender = () => {
  if (!echartInstance) return;
  useTimeoutFn(() => {
    echartInstance.resize();
  }, 180);
};

tryOnUnmounted(() => {
  if (!echartInstance) return;
  echartInstance.dispose();
  echartInstance = null;
  removeResizeListener(buildSectionBar.value, resetRender);
});
</script>

<style lang="scss" scoped>
.buildSectionBar {
  width: 100%;
  height: 100%;
}
</style>
